<?php

namespace App\Modules\Admin\Services;

use App\Facades\UniqID;
use App\Modules\Admin\Models\AdminRoleUser;
use App\Modules\Admin\Repositories\Contracts\AdminMenuRepository;

class AdminMenuService
{
    private $adminMenuRepository;

    public function __construct(AdminMenuRepository $adminMenuRepository)
    {
        $this->adminMenuRepository = $adminMenuRepository;
    }

    /**
     * 获取列表
     *
     * @param array|null $param
     */
    public function getList($param = null)
    {
        try {

            $filter = [];
            $result = $this->adminMenuRepository->paginate($param['per_page'] ?? null, $filter);
            return [];
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    /**
     * 获取详情
     *
     * @param int $id
     * @return object|array
     */
    public function getInfo($id)
    {
        try {
            $result = $this->adminMenuRepository->find($id);
            return $result;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    public function roleMenu($adminUid)
    {
        $adminRoleUser = AdminRoleUser::where("admin_uid", $adminUid)->with(['adminRole' => function ($query) {
            return $query->with(['roleMenu' => function ($query) {
                return $query->with('menu')->get();
            }])->get();
        }])->first();

        $menu = [];
        if ($adminRoleUser->adminRole) {
            foreach($adminRoleUser->adminRole->roleMenu as $item) {
                // dump($item);
                foreach ($item->menu as $v) {
                    array_push($menu,$v->toArray());
                }
            }
        }
        
       

        return ;
    }

    /**
     * 新增
     *
     * @param array $param
     */
    public function add($param)
    {
        try {
            $param['menu_uid'] = UniqID::nextId();

            $adminMenu = $this->adminMenuRepository->store($param);
            return $adminMenu;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    /**
     * 修改
     *
     * @param array $param
     * @param int $id
     */
    public function update($param, $id)
    {
        try {
            $adminMenu = $this->adminMenuRepository->update($param, $id);
            return $adminMenu;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    /**
     * 删除
     *
     * @param int $id
     */
    public function delete($id)
    {
        try {
            $adminMenu = $this->adminMenuRepository->delete($id);

            $result = [];
            if ($adminMenu) {
                $result = 'success';
            } else {
                $result = 'error';
            }
            return $result;

        } catch (\Throwable $th) {
            throw $th;
        }
    }
}
